<template>
  <div class="login-box">
    <h3 class="p-title">发票打印助手</h3>
    <div class="login-bg">
      <img :src="bg" class="bgImg">
    </div>
    <div class="login-page-container">
      <el-form
        :model="ruleForm2"
        :rules="rules2"
        ref="ruleForm2"
        label-position="left"
        label-width="0px"
        class="demo-ruleForm login-container"
        @keyup.enter.native="login()"
      >
        <div class="logo">
          <div class="logo-img">
            <el-avatar :src="headImg"></el-avatar>
          </div>
          <div class="logo-title">
            <h3 style="font-size: 22px;">发票打印助手</h3>
          </div>
        </div>

        <el-tabs v-model="activeName" @tab-click="typeChange" class="activeName">
          <el-tab-pane label="账户登录" name="1" class="my-tabs">
            <el-form-item prop="account">
              <div class="form-item-title">账号</div>
              <el-input type="text" clearable style="width: 78%" v-model="ruleForm2.account" placeholder="手机"></el-input>
            </el-form-item>
            <el-form-item prop="checkPass">
              <div class="form-item-title">密码</div>
              <el-input type="password" show-password style="width: 78%" v-model="ruleForm2.checkPass" placeholder="密码"></el-input>
            </el-form-item>
          </el-tab-pane>

          <el-tab-pane label="手机号登录" name="2">
            <el-form-item prop="phone">
              <div class="form-item-title">手机号</div>
              <el-input type="text" clearable style="width: 78%" v-model="ruleForm2.phone" placeholder="手机"></el-input>
            </el-form-item>
            <el-form-item prop="code">
              <div class="form-item-title">验证码</div>
              <el-input type="text" clearable v-model="ruleForm2.code" placeholder="验证码" style="width: 45%"></el-input>
              <span class="el-link get-code" v-show="verShow" v-loading="phoneLoading" @click="getPhoneCode">获取验证码</span>
              <span class="get-code" v-show="!verShow">{{timer}}秒后重新获取</span>
            </el-form-item>
<!--            <el-form-item prop="account">-->
<!--              <div class="form-item-title">用户名</div>-->
<!--              <el-input type="text" style="width: 78%" v-model="ruleForm2.account" placeholder="请设置用户名"></el-input>-->
<!--            </el-form-item>-->
<!--            <el-form-item prop="checkPass">-->
<!--              <div class="form-item-title">密码</div>-->
<!--              <el-input type="password" style="width: 78%" v-model="ruleForm2.checkPass" placeholder="请设置登录密码"></el-input>-->
<!--            </el-form-item>-->
          </el-tab-pane>
        </el-tabs>
        <el-form-item style="width:100%;margin-bottom: 1px;">
          <div class="el-link regist" v-if="activeName == '1'" @click="register">注册账号</div>
<!--          <div class="forgetPassword" @click="forgetPassword">忘记密码？</div>-->
        </el-form-item>
        <el-form-item style="width:100%;margin-bottom: 10px;">
          <el-button type="primary" style="width:100%;" class="login-btn" @click="login" :loading="logining">登录</el-button>
        </el-form-item>
        <div class="agreement">
          <el-checkbox click="remberuser" v-model="checked" class="el-link remember">以阅读并同意</el-checkbox>
          <el-link type="primary" @click="invoiceContent">发票授权协议</el-link>
        </div>
        <div class="error" :style="{visibility:!error?'hidden':'visible'}">{{errorText}}</div>
      </el-form>
    </div>
    <el-dialog title="发票授权协议" :visible.sync="invoiceDialogVisible" width="40%" :modal-append-to-body='false' :center="true">
      <div v-html="protocolInfo" style="height:600px;overflow: auto;">
      </div>
    </el-dialog>

  </div>
</template>

<script>
import { mapMutations } from "vuex";
import * as commonApi from "api/common";
import * as types from "../store/mutation-types";
import bg from '../assets/img/login-bg1.png'
import headImg from '../assets/img/project.png'
export default {
  data() {
    let checkAccount = (rule, value, callback) => {
      if (this.activeName == '1'){
        if (value === '') {
          callback(new Error('请输入登录账号'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let checkPassword = (rule, value, callback) => {
      if (this.activeName == '1'){
        if (value === '') {
          callback(new Error('请输入登录密码'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    // <!--验证手机号是否合法-->
    let checkTel = (rule, value, callback) => {
      if (this.activeName == '2'){
        if (value === '') {
          callback(new Error('请输入手机号码'))
        } else if (!this.checkMobile(value)) {
          callback(new Error('手机号码不合法'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    let checkCode = (rule, value, callback) => {
      if (this.activeName == '2'){
        if (value === '') {
          callback(new Error('请输入验证码'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }
    return {
      invoiceDialogVisible: false, //协议展示框
      bg: bg, //背景
      headImg: headImg,//logo
      activeName: '1', //登录方式
      logining: false, //登录加载
      phoneLoading: false, //获取验证码加载
      ruleForm2: { // form表单值
        account: "",
        checkPass: "",
        phone: "",
        code: "",
      },
      rules2: { // form 表单验证
        account: [
          {validator: checkAccount, trigger: 'change' }
        ],
        checkPass: [
          {validator: checkPassword, trigger: 'change' }
        ],
        phone: [
          {validator: checkTel, trigger: 'blur' }
        ],
        code: [
          {validator: checkCode, trigger: 'change' }
        ],
      },
      error: false, //错误提示状态
      errorText: '错误',//错误提示内容
      checked: true, //协议勾选
      protocolInfo: '', //协议内容
      verShow: true, //验证码显示控制
      timer: 60, //验证码重新获取倒计时
    };
  },
  created() {
    this.getInvoiceProtocolInfo()
    // this.ruleForm2.checkPass = "";
    // if (localStorage.getItem('userName')) {  // 记住密码操作
    //   this.ruleForm2.account = localStorage.getItem('userName');
    //   this.ruleForm2.checkPass = localStorage.getItem('password');
    // }
  },
  mounted() {
    // 绑定enter事件
    // this.enterKeyup();
  },
  destroyed() {
    // 销毁enter事件
    // this.enterKeyupDestroyed();
  },
  methods: {
    login() {
      this.$refs.ruleForm2.validate(valid => {
        if (valid) {
          if (!this.checked){
            this.showError('请阅读同意协议')
            return
          }
          this.logining = true;
          const params = {}
          params.loginType = this.activeName
          if (this.activeName === '1'){
            params.account = this.ruleForm2.account
            params.password = window.btoa(this.ruleForm2.checkPass)
          } else if (this.activeName === '2'){
            params.phone = this.ruleForm2.phone
            params.code = this.ruleForm2.code
          }
          // 发送API请求
          commonApi.loginUserNo(params).then(res => {
            let { data } = res;
            this.logining = false;
            if (data.status === 200) {
              let userInfo = data.data.user
              sessionStorage.setItem("user", JSON.stringify(userInfo)); // session存储用户信息
              sessionStorage.setItem("mailbox", JSON.stringify(data.data.mailbox)); // session存储邮箱信息
              sessionStorage.setItem("record", JSON.stringify(data.data.record)); // session存储获取记录信息
              if (userInfo.userType == 1){
                this.$router.push({ path: "/guide" });  // 去引导页
              } else {
                this.$router.push({ path: "/invoice/invoiceList" });  // 去主页
              }

              // this.setTreeData(data.data); // 状态存储菜单节点
              // this.setToken(data.value); // 状态存储token
              // sessionStorage.setItem("token", data.value); // session存储token
              // 记住密码操作
              // if (this.checked) {
              //   localStorage.setItem('userName', params.userName)
              //   localStorage.setItem('password', params.password)
              // } else {
              //   localStorage.clear();
              // }
            } else if (data.status === 556){ //手机未注册
              this.$router.push({name:'register', params:{type: '2',phone: this.ruleForm2.phone}})
            }else {
              this.showError(data.msg)
            }
          })
          .catch(() => {
            this.logining = false;
            this.showError("对不起,连接服务器异常,请稍后再试!")
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    typeChange(tab, event) { //登录类型切换
      console.log(tab, event);
    },
    invoiceContent(){ // 查看发票内容
      if (this.protocolInfo === null || this.protocolInfo === '') {
        this.getInvoiceProtocolInfo()
      }
      this.invoiceDialogVisible = true
    },
    register(){
      this.$router.push({ path: "/register" });  // 去注册
    },
    forgetPassword(){
    },
    getPhoneCode(){ // 获取手机验证码
      this.$refs.ruleForm2.validateField('phone' ,valid => { //单个字段检验
        if(!valid){
          this.phoneLoading = true
          let phone = this.ruleForm2.phone
          commonApi.sendPhoneCode(phone, 1).then(res => {
            let { data } = res;
            this.phoneLoading = false
            if (data.status === 200) {
              this.verShow = false
              var auth_timer = setInterval(()=>{ //倒计时
                this.timer--
                if(this.timer<=0){
                  this.verShow = true
                  this.timer = 60
                  clearInterval(auth_timer)
                }
              },1000)
            } else {
              this.showError(data.msg)
            }
          })

        }
      })

    },
    getInvoiceProtocolInfo(){ // 获取协议内容
      commonApi.findProtocolInfo(1).then(res => {
        let { data } = res;
        if (data.status === 200) {
          this.protocolInfo = data.data
        }
      })
    },
    // 验证手机号
    checkMobile(str) {
      let re = /^1\d{10}$/
      if (re.test(str)) {
        return true;
      } else {
        return false;
      }
    },
    enterKey(event) { // 回车事件
      const componentName = this.$options.name;
      if (componentName == "Login") {
        const code = event.keyCode
          ? event.keyCode
          : event.which
            ? event.which
            : event.charCode;
        if (code == 13) {
          this.login();
        }
      }
    },
    showError(t){ //展示错误
      this.errorText = t
      this.error = true
      setTimeout(()=>{
        this.error = false
      }, 5000)
    },
    enterKeyupDestroyed() { //移除键盘事件
      document.removeEventListener("keyup", this.enterKey);
    },
    enterKeyup() { //添加键盘事件
      document.addEventListener("keyup", this.enterKey);
    },
    ...mapMutations({
      setUsername: types.SET_USERNAME,
      setPassword: types.SET_PASSWORD,
      setTreeData: types.SET_TREEDTA,
      setToken: types.SET_TOKEN
    })
  }
};
</script>

<!--组件样式 本页面修改-->
<style scoped lang="scss">
  @import "../assets/css/them.scss";
  .activeName{
    /deep/ .el-tabs__nav-scroll{
      text-align: center;
    }
    /deep/ .el-tabs__header{
      margin: 0 0 30px 0;
    }
    /deep/ .el-tabs__nav{
      float: none;
    }
    /deep/ .el-tabs__item{
      padding: 0 10px;
      color: #000000;
      font-weight:500;
      font-size:14px;
    }
    /deep/ .el-tabs__active-bar{
      background: $baseBgColor;
    }
    /deep/ .el-tabs__item.is-active{
      color: #3B83FB;
      font-weight: 600;
      font-size: 20px;
    }
    /deep/ .el-input__inner{
      height: 32px;
      line-height: 32px;
      border-radius: 6px;
    }
    /deep/ .el-form-item{

    }
    /deep/ .el-form-item__error{
      left: 75px;
    }
  }
  .remember{
    /deep/ .el-checkbox__inner{
      border-radius: 10px;
    }
  }
</style>
<style scoped lang="scss">
@import "../assets/css/them.scss";

@media screen and (max-width: 1200px) {
  .login-box {
    width: 100%;
    height: 100%;
    min-width: 900px;
    position: fixed;
    left: 0;
    top: 0;
    background-color: $globalBgColor;
    background: url("../assets/img/login-bg.png") right no-repeat;
    background-size: 68% 100%;
    .p-title {
      display: inline-block;
      padding: 1% 3%;
      position: absolute;
      font-size: 30px;
    }
    .login-bg{
      position: absolute;
      z-index: -99;
      display: inline-block;
      padding-top: 12%;
      padding-left: 1%;
      .bgImg{
        padding-left: 50px;
        width: 65%;
      }
    }
    .login-page-container{
      display: inline-block;
      float:right;
      padding-right: 6%;
      margin-top: 5vh;
      .login-container {
        -webkit-border-radius: 20px;
        border-radius: 20px;
        -moz-border-radius: 20px;
        background-clip: border-box;
        width: 300px;
        padding: 20px 30px;
        background: $baseBgColor;
        border: 1px solid #eaeaea;
        .logo{
          text-align: center;
          padding: 10px 20px 20px 20px;
          .logo-img{
            display: inline-block;
            position: relative;
            top: 10px;
          }
          .logo-title {
            display: inline-block;
            padding-left: 20px;
          }
        }
        .activeName{
          .form-item-title{
            display: inline-block;
            width: 20%;
            text-align: left;
            color: #333333;
            font-size: 14px;
            font-weight: 400;
          }
          .get-code{
            padding-left: 5px;
            color: #3B83FB;
            font-weight: 400;
            font-size: 12px;
            width: 90px;
          }
        }
        .regist{
          color: #3B83FB;
          display: inline-block;
          font-size: 10px;
          font-weight: 400;
          position: absolute;
          margin-left: 240px;
          margin-top: -32px
        }
        .forgetPassword{
          color: #3B83FB;
          display: inline-block;
          font-size: 10px;
          font-weight: 400;
          float: right;
          padding-right: 30px;
          padding-bottom: 20px;
        }
        .login-btn{
          margin-top: 20px;
          border-radius: 20px;
        }
      }
      .agreement{
        padding-bottom: 5px;
      }
      .error{
        text-align: center;
        color: red;
        font-size: 12px;
      }
    }
  }
}
@media screen and (min-width: 1200px) and (max-width: 1600px){
  .login-box {
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;
    background-color: $globalBgColor;
    background: url("../assets/img/login-bg.png") right no-repeat;
    background-size: 68% 100%;
    .p-title {
      display: inline-block;
      padding: 2% 5%;
      position: absolute;
      font-size: 30px;
    }
    .login-bg{
      position: absolute;
      z-index: -99;
      display: inline-block;
      padding-top: 10%;
      padding-left: 5%;
      .bgImg{
        padding-left: 50px;
      }
    }
    .login-page-container{
      display: inline-block;
      float:right;
      padding-right: 10%;
      margin-top: 10vh;
      .login-container {
        -webkit-border-radius: 20px;
        border-radius: 20px;
        -moz-border-radius: 20px;
        background-clip: border-box;
        width: 300px;
        padding: 20px 30px;
        background: $baseBgColor;
        border: 1px solid #eaeaea;
        .logo{
          text-align: center;
          padding: 20px 20px 30px 20px;
          .logo-img{
            display: inline-block;
            position: relative;
            top: 10px;
          }
          .logo-title {
            display: inline-block;
            padding-left: 20px;
          }
        }
        .activeName{
          .form-item-title{
            display: inline-block;
            width: 20%;
            text-align: left;
            color: #333333;
            font-size: 14px;
            font-weight: 400;
          }
          .get-code{
            padding-left: 5px;
            color: #3B83FB;
            font-weight: 400;
            font-size: 12px;
            width: 90px;
          }
        }
        .regist{
          color: #3B83FB;
          display: inline-block;
          font-size: 10px;
          font-weight: 400;
          position: absolute;
          margin-left: 240px;
          margin-top: -32px
        }
        .forgetPassword{
          color: #3B83FB;
          display: inline-block;
          font-size: 10px;
          font-weight: 400;
          float: right;
          padding-right: 30px;
          padding-bottom: 20px;
        }
        .login-btn{
          margin-top: 20px;
          border-radius: 20px;
        }
      }
      .agreement{
        padding-bottom: 10px;
      }
      .error{
        text-align: center;
        color: red;
        font-size: 12px;
      }
    }
  }
}
@media screen and (min-width: 1600px){
  .login-box {
    width: 100%;
    height: 100%;
    position: fixed;
    left: 0;
    top: 0;
    background-color: $globalBgColor;
    background: url("../assets/img/login-bg.png") right no-repeat;
    background-size: 68% 100%;
    .p-title {
      display: inline-block;
      padding: 2% 5%;
      position: absolute;
      font-size: 36px;
    }
    .login-bg{
      position: absolute;
      z-index: -99;
      display: inline-block;
      padding-top: 12%;
      padding-left: 10%;
      .bgImg{
        padding-left: 50px;
      }
    }
    .login-page-container{
      display: inline-block;
      float:right;
      padding-right: 10%;
      margin-top: 10%;
      .login-container {
        -webkit-border-radius: 20px;
        border-radius: 20px;
        -moz-border-radius: 20px;
        background-clip: border-box;
        width: 300px;
        padding: 35px 35px 15px;
        background: $baseBgColor;
        border: 1px solid #eaeaea;
        .logo{
          text-align: center;
          padding: 20px 20px 40px 20px;
          .logo-img{
            display: inline-block;
            position: relative;
            top: 10px;
          }
          .logo-title {
            display: inline-block;
            padding-left: 20px;
          }
        }
        .activeName{
          .form-item-title{
            display: inline-block;
            width: 20%;
            text-align: left;
            color: #333333;
            font-size: 14px;
            font-weight: 400;
          }
          .get-code{
            padding-left: 5px;
            color: #3B83FB;
            font-weight: 400;
            font-size: 12px;
            width: 90px;
          }
        }
        .regist{
          color: #3B83FB;
          display: inline-block;
          font-size: 10px;
          font-weight: 400;
          position: absolute;
          margin-left: 240px;
          margin-top: -32px
        }
        .forgetPassword{
          color: #3B83FB;
          display: inline-block;
          font-size: 10px;
          font-weight: 400;
          float: right;
          padding-right: 30px;
          padding-bottom: 20px;
        }
        .login-btn{
          margin-top: 20px;
          border-radius: 20px;
        }
      }
      .agreement{
        padding-bottom: 15px;
      }
      .error{
        text-align: center;
        color: red;
        font-size: 12px;
      }
    }
  }
}



</style>


